﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CRM.DataAccess.Entities;
using CRM.Business.Services;
using CRM.Encryption;
using Telerik.Web.UI;

namespace Web.Contact
{
    public partial class AddNewContact : System.Web.UI.Page
    {
        static string prevPage = String.Empty;
        static USER user;
        static ROLE r;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
                return;
            txtPrimaryEmail.Attributes.Add("onblur", "CheckNull();");
            if (Request.UrlReferrer != null)
            {
                prevPage = Request.UrlReferrer.ToString();
                hdntxtPrevPage.Value = prevPage;
            }
            user = (USER)Session["User"];
            if (user != null)
            {
                LoadLoyalty();
                LoadStatus();
                LoaSalutationType();
                LoadLeadSource();
                LoadAllUser();
                LoadStatus();
                              
            }
        }
        private void LoadLoyalty()
        {
            long? assignTo = null;
            r = RoleService.GetRoleByID((long)user.ROLE_ID);
            if ((!(bool)user.IS_ADMIN) && (!(bool)r.IS_MANAGER))
            {
                assignTo = user.ID;
                divAssignTo.Visible = false;
            }
            ddlLoyalty.DataSource = LoyaltyService.ListAll(assignTo);
            ddlLoyalty.DataBind();
        }
        private void LoadAllUser()
        {
            ddlAssignedTo.Items.Clear();
            List<USER> users = UserService.ListAll();
            if (users != null)
            {
                foreach (USER u in users)
                {
                    ddlAssignedTo.Items.Add(new RadComboBoxItem(u.SUR_NAME + " " + u.NAME, u.ID.ToString()));
                }
            }
        }
        private void LoadLeadSource()
        {
            ddlLeadSource.DataSource = LeadSourceService.GetAllLeadSource();
            ddlLeadSource.DataBind();
        }
        private void LoaSalutationType()
        {
            ddlSalutationType.DataSource = SalutationService.GetAllSalutatioin();
            ddlSalutationType.DataBind();
        }
        private void LoadStatus()
        {
            ddlStatus.DataSource = ContactService.GetAllContactStatus();
            ddlStatus.DataBind();
        }
        private int addNewContact()
        {
            CONTACT contact = new CONTACT();
            // BASIC INFORMATION
            contact.SALUTATION_ID = Convert.ToInt64(ddlSalutationType.SelectedItem.Value);
            contact.SUR_NAME = txtSurname.Text.Trim();
            contact.NAME = txtLastName.Text.Trim();
            contact.PHONE_OFFICE = txtOfficePhone.Text.Trim();
            if (hdntxtOrgID.Value == "")
                contact.ORGANIZATION_ID = null;
            else
                contact.ORGANIZATION_ID = Convert.ToInt64(hdntxtOrgID.Value);
            contact.PHONE_MOBILE = txtMobilePhone.Text.Trim();
            contact.LEAD_SOURCE_ID = Convert.ToInt64(ddlLeadSource.SelectedItem.Value);
            contact.PHONE_HOME = txtHomePhone.Text.Trim();
            contact.DESIGNATION = txtDesignation.Text.Trim();
            contact.PHONE_SECONDARY = txtSecondaryPhone.Text.Trim();
            contact.DEPARTMENT = txtDepartment.Text.Trim();
            contact.FAX = txtFax.Text.Trim();
            contact.PRIMARY_EMAIL = txtPrimaryEmail.Text.Trim();
            contact.DATE_OF_BIRTH = dpDateOfBirth.SelectedDate;
            contact.STATUS_ID = Convert.ToInt64(ddlStatus.SelectedItem.Value);
            
            if ((!(bool)user.IS_ADMIN) && (!(bool)r.IS_MANAGER))
                contact.ASSIGNED_USER_ID = user.ID;
            else
            {
                if (ddlAssignedTo.SelectedItem == null)
                    contact.ASSIGNED_USER_ID = null;
                else
                    contact.ASSIGNED_USER_ID = Convert.ToInt64(ddlAssignedTo.SelectedItem.Value);
            }
            if (ddlLoyalty.SelectedValue != "-1")
            {
                contact.LOYALTY_ID = Convert.ToInt64(ddlLoyalty.SelectedValue);
                contact.LOYALTY_STARTER_ID = contact.LOYALTY_ID;
                contact.LOYALTY_NAME = ddlLoyalty.SelectedItem.Text;
            }
            contact.POINTS = 0;
            DateTime dt = DateTime.Now;
            contact.DATE_ENTERED = dt;
            contact.DATE_MODIFIED = dt;
            //  CUSTOMER PORTAL DETAILS
            contact.SUPPORT_START_DATE = dpSupportStartDate.SelectedDate;
            contact.SUPPORT_END_DATE = dbSupportEndDate.SelectedDate;

            // ADDRESS DETAILS
            contact.OFFICE_STREET = txtOfficeStreet.Text.Trim();
            contact.HOME_STREET = txtHomeStreet.Text.Trim();
            contact.OFFICE_PO_BOX = txtOfficePOBox.Text.Trim();
            contact.HOME_PO_BOX = txtHomePOBox.Text.Trim();
            contact.OFFICE_CITY = txtOfficeCity.Text.Trim();
            contact.HOME_CITY = txtHomeCity.Text.Trim();
            contact.OFFICE_STATE = txtOfficeState.Text.Trim();
            contact.HOME_STATE = txtHomeState.Text.Trim();
            contact.OFFICE_ZIP = txtOfficeZip.Text.Trim();
            contact.HOME_ZIP = txtHomeZip.Text.Trim();
            contact.OFFICE_COUNTRY = txtOfficeCountry.Text.Trim();
            contact.HOME_COUNTRY = txtHomeCountry.Text.Trim();
            //Status info
            APPOINTMENT appoint = null;
            QUOTATION_ISSUES qiss = null;
            DEPOSIT_COLLECTIONS dc = null;
            PROCESS_ORDERS po = null;
            PAYMENT_COLLECTIONS paid = null;
            if (ddlStatus.SelectedValue == "1")
            {
                appoint = new APPOINTMENT();
                appoint.APPOINTMENT1 = rbtnAppointmentYes.Checked;
                appoint.NO_REASON = rbtnAppointmentYes.Checked ? null : txtAppointmentNoReason.Text.Trim();
                contact.STATUS_FINAL_STEP = "1";
                qiss = getQuotationIssue((bool)appoint.APPOINTMENT1);
                if (qiss != null) contact.STATUS_FINAL_STEP = "2";
                dc = qiss != null ? getDepositCollection((bool)qiss.QUOTATION_ISSUE) : null;
                if (dc != null)
                {
                    contact.STATUS_FINAL_STEP = "31";
                    if (dc.DEPOSIT_INVOICE_ISSUE != null)
                        contact.STATUS_FINAL_STEP = "32";
                }
                po = dc != null ? getProcessOrder(dc.DEPOSIT_INVOICE_ISSUE == null ? false : (bool)dc.DEPOSIT_INVOICE_ISSUE) : null;
                if (po != null) contact.STATUS_FINAL_STEP = "4";
                paid = po != null ? getPaymentCollection(po.FULL_INVOICE_ISSUE == null ? false : (bool)po.FULL_INVOICE_ISSUE) : null;
                if (paid != null) contact.STATUS_FINAL_STEP = "5";
            }
            return ContactService.AddNewContact(contact, appoint, qiss, dc, po, paid);
        }
        private PAYMENT_COLLECTIONS getPaymentCollection(bool poFullIIYes)
        {
            PAYMENT_COLLECTIONS paid = null;
            if (poFullIIYes && hdntxtNextStep4Clicked.Value == "1")
            {
                paid = new PAYMENT_COLLECTIONS();
                paid.PAYMENT_COLLECTION = rbtnPaidYes.Checked;
                paid.NO_REASON = (bool)paid.PAYMENT_COLLECTION ? null : txtPaidNoReason.Text.Trim();
                paid.IS_CLOSE_CASE = paid.PAYMENT_COLLECTION;
            }
            return paid;
        }
        private PROCESS_ORDERS getProcessOrder(bool dcDIIYes)
        {
            PROCESS_ORDERS po = null;
            if (dcDIIYes && hdntxtNextStep3Clicked.Value == "1")
            {
                po = new PROCESS_ORDERS();
                po.IS_PENDING = ddlPOStatus.SelectedValue == "0" ? true : false;
                po.PENDING_DATE = (bool)po.IS_PENDING ? dpPOPendingDate.SelectedDate : null;
                po.IS_COMPLETED = ddlPOStatus.SelectedValue == "1" ? true : false;
                if ((bool)po.IS_COMPLETED)
                    po.FULL_INVOICE_ISSUE = rbtnPOFullIIYes.Checked;
            }
            return po;
        }
        private DEPOSIT_COLLECTIONS getDepositCollection(bool qissYes)
        {
            DEPOSIT_COLLECTIONS dc = null;
            if (qissYes && hdntxtNextStep2Clicked.Value == "1")
            {
                dc = new DEPOSIT_COLLECTIONS();
                dc.DEPOSIT_COLLECTED = rbtnDCYes.Checked;
                dc.NO_REASON = (bool)dc.DEPOSIT_COLLECTED ? null : txtDCNoReason.Text.Trim();
                dc.AMOUNT = (bool)dc.DEPOSIT_COLLECTED ? rntxtAmount.Value : null;
                if ((bool)dc.DEPOSIT_COLLECTED && (dc.AMOUNT != null && dc.AMOUNT.Value != 0))
                {
                    dc.DEPOSIT_INVOICE_ISSUE = rbtnDCDIIYes.Checked;
                    dc.NO_DEPOSIT_INVOICE_ISSUE_REASON = (bool)dc.DEPOSIT_INVOICE_ISSUE ? null : txtDCDIINoReason.Text.Trim();
                }
            }
            return dc;
        }
        private QUOTATION_ISSUES getQuotationIssue(bool appointment)
        {
            QUOTATION_ISSUES qiss = null;
            if (appointment && hdntxtNextStep1Clicked.Value == "1")
            {
                qiss = new QUOTATION_ISSUES();
                qiss.QUOTATION_ISSUE = rbtnQuotationIssueYes.Checked;
                if (!(bool)qiss.QUOTATION_ISSUE)
                {
                    qiss.IS_PENDING = ddlQINoReason.SelectedValue == "0" ? true : false;
                    qiss.IS_REJECTED = ddlQINoReason.SelectedValue == "1" ? true : false;
                    if ((bool)qiss.IS_REJECTED)
                    {
                        qiss.REJECTED_REASON = txtQIRejectedReason.Text.Trim();
                    }
                    if ((bool)qiss.IS_PENDING)
                    {
                        qiss.IS_CALL_BACK = ddlQIPendingReason.SelectedValue == "0" ? true : false;
                        qiss.IS_APPOINTMENT = ddlQIPendingReason.SelectedValue == "1" ? true : false;
                    }
                }
            }
            return qiss;
        }
        protected void btn_Save_Click(object sender, EventArgs e)
        {
            
            int newContactResult = addNewContact();
            if (newContactResult == 1)
            {
                RadAjaxManager.GetCurrent(this).ResponseScripts.Add(@"ShowMessageAndRedirect('" + "Add new contact successful !" + "','" + "Contacts.aspx" + "');");
                //MessageBox.Show(this.Page, Page.GetType(), "Add new contact successful !", "Contacts.aspx");
            }
            else
                RadAjaxManager.GetCurrent(this).ResponseScripts.Add(@"ShowMessage('" + "Can not add new contact !" + "');");
                //RadScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert('Can not add new contact !');", true);
        }
        protected void btn_Cancel_Click(object sender, EventArgs e)
        {
            Response.Redirect(prevPage);
        }
    }
}